package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description: 上传图片文件实现类
 * User: Spider-Man
 * Date: 2025-09-11
 * Time: 13:10
 */
@Component
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}") //从配置文件读取数据
    private String localPath;
    @Override
    public String savePicture(MultipartFile multipartFile) {
        //1.创建保存图片的文件目录.
        File dir = new File(localPath);
        if(!dir.exists()) {
            dir.mkdirs();//如果创建a/v/x 这个目录, 但是其中v目录不存在,那么就会自动帮我们创建
        }
        //2.创建索引 (根据文件名进行转换)
        //aaa.jpg -> xxx.jpc
        //2.1获取当前上传文件名
        String filename =  multipartFile.getOriginalFilename();//获取文件名
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf(".")); //获取到文件格式
        filename = UUID.randomUUID() + suffix;//生成索引

        //图片保存
        //将multipartFile放入到我们的目标文件当中
        //目标文件: new File(localPath + "/" + filename)
        try {
            multipartFile.transferTo(new File(localPath + "/" + filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }

        return filename;
    }
}
